<template>
  <div class="app-container">
    <div class="filter-container">

      <el-select v-model="searchOptions.appointName" placeholder="服务名称" clearable style="width: 130px" class="filter-item">
        <el-option v-for="item in appointInfo" :key="item.appointName" :label="item.appointName" :value="item.appointName" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <!-- {{ searchOptions }} -->

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      stripe
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />
      <el-table-column show-overflow-tooltip label="订单号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.appointName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="申请人" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="学号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stuId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系方式" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tel }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderDesc }}</span>
        </template>
      </el-table-column>

      <el-table-column label="订单进度" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.orderProcess==0" color="#eebe77" style="color: rgb(255, 255, 255);border: none;">
            待处理
          </el-tag>
          <el-tag v-else-if="row.orderProcess==1" color="#95d475" style="color: rgb(255, 255, 255);border: none;">
            处理中
          </el-tag>
          <el-tag v-else-if="row.orderProcess==2" color="#79bbff" style="color: rgb(255, 255, 255);border: none;">
            已完成
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="预约时间" width="120" align="center">
        <template slot-scope="{row}">
          <div>{{ row.orderTime.split(' ')[0] }}</div>
          <div>{{ row.orderTime.split(' ')[1] }}</div>
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.status!='deleted'" size="mini" type="success" @click="handleComplete(row,$index)">
            完成订单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { fetchAppoint, fetchAppointOrder, updateAppointOrder } from '@/api/appoint'
import { MessageBox } from 'element-ui'

export default {
  name: 'AppointOrder',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      appointInfo: [],
      infoTitle: '详情',
      ori_data: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20
      },
      searchOptions: {
        appointName: ''
      },
      dormitoryOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
      failureTypeOptions: ['网速太慢', '无法上网', '其他原因'],
      orderProcessOptions: ['待处理', '处理中', '已完成'],
      showReviewer: false,
      temp: {
        createTime: '',
        deleted: '',
        id: '',
        nickName: '',
        orderId: '',
        orderProcess: '',
        orderTime: '',
        staffId: '',
        stuId: '',
        tel: '',
        updateTime: '',
        urgedCount: '',
        userName: '',
        employeeIdName: '',
        employeeInfo: { nickName: '', staffId: '', staffTel: '' }
      },
      dialogFormVisible: false,
      dialogINFOFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
        info: '详情'
      },
      downloadLoading: false,
      rules: {
        orderProcess: [{ required: true, message: '必填', trigger: 'change' }],
        employeeIdName: [{ required: false, message: '请选择师傅', trigger: 'change' }]
      }
    }
  },
  created() {
    const appointName = this.$route.query.appointName
    if (appointName) {
      this.searchOptions.appointName = appointName
    }
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true

      fetchAppoint().then(response => {
        this.appointInfo = response.data.data
        console.log(this.appointInfo)
      })

      fetchAppointOrder(this.listQuery).then(response => {
        const orderInfo = response.data.data
        this.ori_data = orderInfo.records
        this.list = this.ori_data
        this.alltotal = orderInfo.total
        this.total = orderInfo.total

        if (this.searchOptions.appointName !== '') {
          this.handleFilter()
        }

        setTimeout(() => {
          this.listLoading = false
        }, 0.6 * 1000)
      })
    },
    handleFilter() {
      const appointName = this.searchOptions.appointName
      let result = this.ori_data
      if (appointName !== '') {
        result = result.filter(item => {
          return item.appointName === appointName
        })
      }

      this.list = result
      this.total = result.length
      if (appointName === '') {
        this.list = this.ori_data
        this.total = this.alltotal
      }

      // console.log(result)
    },
    resetTemp() {
      this.temp = {
      }
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['订单号', '服务名称', '申请人', '学号', '联系方式', '备注', '订单进度', '预约时间', '创建时间']
        const filterVal = ['orderId', 'appointName', 'nickName', 'stuId', 'tel', 'orderDesc', 'orderProcess', 'orderTime', 'createTime']
        const data = this.formatJson(filterVal)
        // console.log(data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '服务订单'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v =>
        filterVal.map(j => {
          if (j.split('.')[0] === 'detail') {
            // console.log(v['detail'][j.split('.')[1]])
            return v['detail'][j.split('.')[1]]
          } else {
            // console.log(v[j])
            return v[j]
          }
        })
      )
    },
    handleComplete(row, index) {
      var tempData = row
      MessageBox.confirm('是否完成订单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateAppointOrder({ 'id': row.id, 'orderProcess': 2 }).then(res => {
          tempData.orderProcess = 2
          this.$notify({
            title: '成功',
            message: '订单已完成',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1, tempData)
        })
      })
    }
  }}

</script>
